//
//  PageDetector.swift
//  SwiftCode
//
//  Created by yuhus on 2024/8/2.
//

import Foundation
import UIKit

class PageDetector {
  init() {
//    UIViewController.swizzleViewWillAppear()
    UIViewController.swizzleViewDidAppear()
  }
}
extension UIViewController {
  @objc func logging_viewWillAppear(_ animated: Bool) {
    log("\(self) start")
    self.logging_viewWillAppear(animated)
  }
  
  @objc func time_viewDidAppear(_ animated: Bool) {
    log("\(self) start")
    self.time_viewDidAppear(animated)
  }
  
  static func swizzleViewWillAppear() {
    print(#fileID, #function, #line)
    let originalSelector = #selector(viewWillAppear(_:))
    let swizzledSelector = #selector(logging_viewWillAppear(_:))
    
    guard let originalMethod = class_getInstanceMethod(self, originalSelector),
          let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) else {
      return
    }
    print(#fileID, #function, #line)
    method_exchangeImplementations(originalMethod, swizzledMethod)
  }
  
  static func swizzleViewDidAppear() {
    log("start")
    let originalSelector = #selector(viewDidAppear(_:))
    let swizzledSelector = #selector(time_viewDidAppear(_:))
    
    guard let originalMethod = class_getInstanceMethod(self, originalSelector),
          let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) else {
      return
    }
    log("end")
    method_exchangeImplementations(originalMethod, swizzledMethod)
  }
}

private func log(_ items: Any..., category: String? = nil, file: String = #fileID, method: String = #function, line: Int = #line) {
  let message = items.map { String(describing: $0) }.joined(separator: "")
  DispatchQueue.global().async {
    print(Date(), file, method, line, message)
  }
}

